package com.javaee.websocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class WebSocketTest {
	
	 private static CopyOnWriteArraySet<WebSocketTest> sessions = new CopyOnWriteArraySet<WebSocketTest>();
	 private  Session session;
	 
	 
	 @OnMessage  
	    public void onMessage(String message,Session session) throws IOException, InterruptedException {  
		 try {
	            if (sessions.size() != 0) {
	                for (WebSocketTest s : sessions) {
	                    if (s != null) {
//	                         s.session.getBasicRemote().sendText(message); //群发
	                    	System.out.println("从客户端接收到的信息: " + message);  
	            	       
	                     }
	            }
	                session.getBasicRemote().sendText("即时发送信息 : " + message); //单个发,当前用户
	        }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }  
	    /** 
	     * 当一个新用户连接时所调用的方法 
	     * 该方法可能包含一个javax.websocket.Session可选参数 
	     * 如果有这个参数，容器将会把当前发送消息客户端的连接Session注入进去 
	     */  
	    @OnOpen  
	    public void onOpen(Session session) {  
	        System.out.println("客户端连接成功");
	        this.session = session;
	        sessions.add(this);
	    }  
	    /** 当一个用户断开连接时所调用的方法*/  
	    @OnClose  
	    public void onClose() {  
	        System.out.println("客户端关闭");
	        sessions.remove(this);
	    }  
	    
}
